package com.jar.netty_demo.BIO;

import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * BIO模型
 */
public class NettyDemo {
    public static void main(String[] args) throws IOException {
        //创建一个线程池
        ExecutorService executorService = Executors.newCachedThreadPool();
        ServerSocket serverSocket = new ServerSocket(9999);
        System.out.println("服务器启动了");
        while (true) {
            Socket socket = serverSocket.accept();
            System.out.println("有一个客户端链接上来了");
            executorService.execute(() -> {
                //业务
                execute(socket);
            });
        }


    }

    public static void execute(Socket socket) {
        InputStream input = null;
        try {
            System.out.println("线程信息id=" + Thread.currentThread().getId() + "名字=" + Thread.currentThread().getName());
            input = socket.getInputStream();
            byte[] bytes = new byte[1024];
            int m = 0;
            while ((m = input.read(bytes)) != -1) {
                System.out.println(new String(bytes, 0, m));
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (input != null) {
                    input.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
